import React from "react";
import FieldContext from "./FieldContext";
import useForm from "./useForm";

interface IForm {
  children: any;
  form: IUseForm;
  onFinish: Function;
  onFinishFailed: Function;
}

function Form(
  { form, children, onFinishFailed, onFinish }: IForm,
  ref: any
): JSX.Element {
  const [formInstance] = useForm(form);

  // 在使用Form组件的时候，传ref就会拿到组件实例方法，不传不影响
  React.useImperativeHandle(ref, () => formInstance);

  formInstance.setCallbacks({ onFinishFailed, onFinish });

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        formInstance.submit()
      }}
    >
      <FieldContext.Provider value={formInstance}>
        {children}
      </FieldContext.Provider>
    </form>
  );
}

export default Form;
